<template>
  <div class="login-container">
    <!-- NavBar 组件：只需提供 title 标题 -->
    <van-nav-bar title="黑马头条 - 登录" fixed />
    <!-- 登录表单 -->
    <van-form @submit="login">
      <van-field
        v-model="form.mobile"
        type="tel"
        label="手机号"
        placeholder="请输入手机号"
        required
        :rules="rules.mobile"
      ></van-field>
      <van-field
        v-model="form.code"
        type="password"
        label="密码"
        placeholder="请输入密码"
        required
        :rules="rules.code"
      ></van-field>
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >LOG IN</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginAPI } from '@/api/userapi.js'
import { mapMutations } from 'vuex'
export default {
  name: 'Login',
  data () {
    return {
      form: {
        mobile: '18119254032',
        code: '246810'
      },
      rules: {
        mobile: [{ required: true, trigger: 'onBlur' }, { pattern: /^1\d{10}$/, message: '请填写正确的手机号', trigger: 'onBlur' }],
        code: [{ required: true, trigger: 'onBlur' }]
      }
    }
  },
  methods: {
    ...mapMutations(['updateTokenInfo']),
    async login () {
      const { data: res } = await loginAPI(this.form)
      // 把token存到state中
      if (res.message === 'OK') {
        // 3. 把登录成功的结果，存储到 vuex 中
        this.updateTokenInfo(res.data)
        // 4. 登录成功后，跳转到主页
        // 优化增加判断，如果，用户是准备进入用户页而被判断未登录，强制进入登录页的，路由规则中会携带query参数pre
        if (this.$route.query.pre) {
          // 如果携带，跳转到携带的pre地址
          this.$router.push(this.$route.query.pre)
        } else {
          // 未携带，默认跳转
          this.$router.push('/')
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
.login-container {
  padding-top: 46px;
}
</style>
